import utils from "@/utils/utils.js";
import apis from "@/api/index.js";//全局API
import { getToken, setToken, removeToken } from '@/utils/auth'
import axios from 'axios'
import config from "@/config/index.js";


const useCounter = defineStore('counter', {
  state: () => {
    return {
      token: getToken(),
      depts: [],
      yiniaoAdmin: {},
      permissionHasLoaing: false
    }
  },
  getters: {
    //部门树
    depsTree: (state) => {
      return utils.transformArray([...state.depts], "_id", "parentId")
    }
  },
  actions: {
    //上传图片
    async uploadFile(file) {
      // let name = file.name
      //console.log("file", file)
      let qnToken = await apis.qiniuToken()
      //定义FormData对象 存储文件
      let mf = new FormData();
      //将图片文件放入mf
      mf.append("file", file);
      mf.append("token", qnToken);
      return new Promise((resolve, reject) => {
        axios({
          url: "https://upload-z2.qiniup.com",
          method: "post",
          data: mf,
        })
          .then((data) => {
            let url = `${config.qiNiuUrl}/${data.data.fileUrl.trim()}`
            resolve(url);
          })
          .catch(function (err) {
            reject(err)
          });
      });
    },

    //获取路由
    getRouter() {
      let yiniaoAdmin = localStorage.getItem('yiniaoAdmin')
      if (!yiniaoAdmin) return
      let { menuList } = JSON.parse(yiniaoAdmin)
      let items = utils.transformArray(menuList, 'id', "parentId")  //整理成树结构
      let array = utils.sortItems(items, "asc", "sort"); //根据升序进行排序
      let newRouter = this.convertToVueRoutes(utils.deepcopy(array));
      //console.log("新路由", newRouter)
      return newRouter
    },

    //设置element路由
    convertToVueRoutes(array) {
      let routes = <any>[];
      array.forEach((element) => {
        let router = {
          path: element.parentId == 0 ? `/${element.menuUri}` : element.menuUri,
          component: setComponent(element),
          name: element.menuUri,
          meta: {
            title: element.name,
            icon: element.menuIcon ? element.menuIcon : "#",
            link: null,
            noCache: false,
          },
          hidden: element.enableStatus == 2 ? true : false,
        };
        if (element.parentId == 0) {
          router["alwaysShow"] = true;
          router["redirect"] = "noRedirect";
        }
        if (element.children && element.children.length) {
          router["children"] = this.convertToVueRoutes(element.children);
        }
        routes.push(router);
      });
      return routes

      function setComponent(element) {
        let yiniaoAdmin = localStorage.getItem('yiniaoAdmin')
        if (!yiniaoAdmin) return
        let { menuList } = JSON.parse(yiniaoAdmin)
        if (element.parentId == 0) return "Layout"  //如果是第一级
        let index = utils.findIndexByField(menuList, "id", element.parentId);
        if (index >= 0) return `${menuList[index].menuUri}/${element.menuUri}`;
      }
    }
  }
})

export default useCounter